#!/usr/bin/python
# coding=utf8
###############################################################################
#                                                                             #
#    Copyright 2007 Danil Dotsenko                                            #
#                                                                             #
#    This program is free software; you can redistribute it and/or modify     #
#    it under the terms of the GNU Lesser General Public License as published #
#    by the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU Lesser General Public License for more details.                      #
#                                                                             #
#    You should have received a copy of the GNU Lesser General Public License #
#    along with this program; if not, write to the Free Software              #
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA #
#                                                                             #
###############################################################################                                   #
# contacts: Danil Dotsenko, dd@accentsolution.com                           #

def __ini2dict__(text):
	'''
	Very basic ini-style text parser. Only treats '=' as key, value separators.
	Takes either a list type of separate lines, or one string/unicode type
	which it splits and strips.
	Returns a dict object with converted contents of the text.
	'''
	#text = '[version]\nwebserver=12334\n\n[other section]\nkey=value\n'
	if not type(text)==type([]):
		text = [ i.strip() for i in text.splitlines() if i] # throwing away empty lines, removing extra spaces.
	root = {}
	active = root # if no sections are found, all key, value pairs are assigned to root.
	for i in text:
		if i[0]=='[' and i[len(i)-1]==']':
			# section name
			i = i.strip('[]')
			root[i]={}
			active = root[i]
		else:
			# key, value pair
			try:
				key, value = i.split('=',1)
			except:
				key, value = i, ''
			active[key]=value
	return root


def getUserFiles():
	'''
	This will help you identify all vCard files user selected 
	(connected) in Kaddressbook  (KDE)
	We return a list of full local paths to each file.
	'''
	from commands import getoutput
	import os
	try:
		cfgdirs = getoutput('kde-config --path config').split(':')
	except:
		cfgdirs = ''
	a = {}
	for path in cfgdirs:
		# found user's address book settings file.
		try:
			a = __ini2dict__(open(path+'kresources/contact/stdrc').read())
			# this is now a dict object with the contents of the rc file.
			break
		except:
			pass
	filenames = []
	if a: 
		b = [a[i] for i in a if i.count('Resource_')] # now, b is a list of sections with Resource_ in the name.
		for i in b:
			try:
				vcard = bool(i['FileFormat']=='vcard')
				active = bool(i['ResourceIsActive']=='true')
			except:
				vcard = False
				active = False
			if vcard and active: # there are 2.5 types of vCard entries in the kde contacts file
				if i.has_key('FileName'): # the single vCard file
					filenames.append(i['FileName'].replace('$HOME', os.environ['HOME']))
				elif i.has_key('FilePath'): # the vCard folder (folder with vCard files)
					path = i['FilePath'].replace('$HOME', os.environ['HOME']) + '/'
					try:
						filenames.extend([path+j for j in os.listdir(path)])
					except:
						pass
				else: # this is the "half" part. if no path is specified, use kde default 
					filenames.append(os.environ['HOME']+'/.kde/share/apps/kabc/std.vcf')
	return filenames

if __name__ == '__main__':
	print "The following vCard files are found:"
	for i in getUserFiles():
		print i